// chat/chat.js
Page({
  id: 0,
  /**
   * 页面的初始数据
   */
  data: {
    message: null,
    newsList: [],
    scrollTop: 0
  },
  onReady() {
    wx.connectSocket({
      url: 'ws://127.0.0.1:2811',
    })
    wx.onSocketOpen((result) => {
      wx.sendSocketMessage({
        data: '你好'
      })
    })
    wx.onSocketMessage((msg) => { // 服务端的信息
      const data = JSON.parse(msg.data)
      data.role = 'server'
      data.id = ++this.id
      let list = [...this.data.newsList]
      list.push(data)
      this.setData({
        newsList: list,
        message: null
      })
      this.rollingBottom()
    })
  },
  rollingBottom() {
    let s = 0
    const list = wx.createSelectorQuery().selectAll('.list')
    list.boundingClientRect(rects => {
      rects.forEach(rect => {
        this.setData({
          scrollTop: rect.bottom
        })
      })
    }).exec()
  },
  send() {
    if (this.data.message) {
      wx.sendSocketMessage({
        data: this.data.message,
      })
      let list = []
      list = [...this.data.newsList]
      var temp = {
        id: this.id++, // id　　　
        content: this.data.message, // 输入的内容20　　　　// 系统时间，引用utils/util.js 中formatTimeNew函数21　　　　
        date: new Date(),
        role: 'me' // 角色23　　　
      }
      list.push(temp)
      this.setData({
        newsList: list,
        message: null
      })
    } else {
      wx.showToast({
        title: '消息不能为空哦～ ',
        icon: 'none ',
        duration: 1000
      })
    }
    this.rollingBottom()
  },
  onUnload() {
    wx.onSocketClose((result) => {
      console.log('已关闭')
    })
  },
})
